package com.azt.provider.impl;

import com.azt.api.dto.MsgSendDto;
import com.azt.api.dto.UserMsgDto;
import com.azt.api.pojo.*;
import com.azt.api.service.MqProducerService;
import com.azt.api.service.MsgConfigService;
import com.azt.model.page.Pagination;
import com.azt.provider.mapper.ConfigMapper;
import com.azt.provider.mapper.MsgConfigMapper;
import com.azt.provider.mapper.MsgUserMapper;
import com.azt.utils.PatternUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@Transactional
public class MsgConfigServiceImpl implements MsgConfigService
{

    private static final Logger log = LoggerFactory.getLogger(MsgConfigServiceImpl.class);

	@Autowired
	private MsgConfigMapper mm;

    @Autowired
    private ConfigMapper cm;


    @Override
    public Pagination getAztMsgPage(int pageno, int pagesize, Map<String, String> searchMap)
    {
        Page<Object> startPage = PageHelper.startPage(pageno, pagesize);
		List<MsgConfig> contentList = mm.getMsgConfigByParams(searchMap);
		Pagination p = new Pagination(startPage, contentList);
		p.setList(contentList);
		p.setParams(searchMap);
        return p;

    }

    @Override
    public void saveMsg(MsgConfig aztMsg)
    {
        mm.insert(aztMsg);
    }

    @Override
    public void deleteAllById(Integer id)
    {
        mm.deleteByPrimaryKey(id);
    }

    @Override
    public void saveEdit(MsgConfig aztmsg)
    {
    	mm.updateByPrimaryKey(aztmsg);
    }


 	@Override
 	public MsgConfig queryById(Integer id)
 	{
 		return mm.selectByPrimaryKey(id);
 	}

    @Override
    public boolean findOrtherMsg(MsgConfig aztmsg)
    {
        List<MsgConfig> aztmsgs = null;
        Integer id = aztmsg.getId();
        String code = aztmsg.getCode();
        if (id != null && !"".equals(id))
        {
            Example exp = new Example(MsgConfig.class);
            exp.createCriteria().andCondition(" code = '"+ code + "' and id <> "+id);
            aztmsgs = mm.selectByExample(exp);
        }
        else
        {
            Example exp = new Example(MsgConfig.class);
            exp.createCriteria().andCondition(" code = '"+ code + "'");
            aztmsgs = mm.selectByExample(exp);
        }
        if (aztmsgs.size() > 0)
        {
            return true;
        }

        return false;
    }

    @Autowired
    private MqProducerService mqs;

    @Autowired
    private MsgUserMapper mum;

    @Override
    public void sendMessage(String code, Map<String, String> params) {
        sendMessage(code, params, null, Collections.emptyList());
    }

    @Override
    public void sendMessage(String code, Map<String, String> params, String url, List users ) {
        sendMessage(code,params,url,users,false);
    }

    public void sendMessage(String code, Map<String, String> params, String url, List users ,boolean delay) {
        try {
            if (StringUtils.isNotBlank(code)) {
                Example exp = new Example(MsgConfig.class);
                exp.createCriteria().andEqualTo("code", code);
                List<MsgConfig> msgConfigs = mm.selectByExample(exp);
                if (CollectionUtil.isNotEmpty(msgConfigs)) {
                    MsgConfig mc = msgConfigs.get(0);
                    mc.setTelContent(replaceContent(mc.getTelContent(), params));
                    mc.setMailContent(replaceContent(mc.getMailContent(), params));
                    mc.setEmailContent(replaceContent(mc.getEmailContent(), params));
                    mc.setTitle(replaceContent(mc.getTitle(), params));
                    List<MsgUser> mus = new ArrayList<MsgUser>();//保存到u_msg_user表里的集合
                    List<String> emails = new ArrayList<String>();//发送邮件的邮箱集合
                    List<String> mobiles = new ArrayList<String>();/*发送短信的手机号集合*/

                    if (users != null && users.size() > 0) {
                        for (Object o : users) {
                            UserMsgDto dto = new UserMsgDto();
                            if (o instanceof UserMsgDto) {
                                dto = (UserMsgDto) o;
                            } else if (o instanceof Integer) {
                                dto = mm.getUserDtoById(Integer.parseInt(o.toString()));
                            }
                            List<MsgSendDto> msgSendDtos = mm.ifCanSendByCAI(dto.getUserId(), code, dto.getEmail(), dto.getMobile());//根据code、userId、email和mobile查询发送的类型 以及 mobile和email
                            if (CollectionUtil.isNotEmpty(msgSendDtos)) {
                                MsgSendDto msgSendDto = msgSendDtos.get(0);
                                MsgUser mu = new MsgUser(dto.getUserId(), mc.getMsgType(), mc.getTitle(), url);
                                mu.setDelay(delay ? 1 : 0);
                                mu.setSorttime(new Date());

                                boolean flag = false;//立个flag
                                if (msgSendDto.getIfEmail().compareTo(1) == 0 && msgSendDto.getEmail() != null && PatternUtils.isEmail(msgSendDto.getEmail())) {//可以发送邮件
                                    emails.add(msgSendDto.getEmail());
                                    mu.setEmail(msgSendDto.getEmail());
                                    mu.setIfEmail(1);
                                    mu.setEmailContent(mc.getEmailContent());
                                    flag = true;
                                }
                                if (msgSendDto.getIfMobile().compareTo(1) == 0 && msgSendDto.getMobile() != null && PatternUtils.isMobile(msgSendDto.getMobile())) {//可以发送短信
                                    mobiles.add(msgSendDto.getMobile());
                                    mu.setMobile(msgSendDto.getMobile());
                                    mu.setIfMobile(1);
                                    mu.setMobileContent(mc.getTelContent());
                                    flag = true;
                                }
                                if (msgSendDto.getIfMail().compareTo(1) == 0 && dto.getUserId() != null) {//当可以发送站内信时
                                    //MsgUser  mu = new MsgUser(dto.getUserId() , mc.getMsgType() , mc.getTitle() , mc.getMailContent() , url , msgSendDto.getIfMail() , msgSendDto.getIfMobile() , msgSendDto.getIfEmail());
                                    flag = true;
                                    mu.setIfMail(1);
                                    mu.setMsgContent(mc.getMailContent());
                                }
                                if (flag) {
                                    mus.add(mu);
                                }
                            }
                        }
                    } else if (StrUtil.isNotBlank(mc.getAppointTels())) {//发送给短消息中设置的固定人员  适用于发送给安装通客服之类的。
                        String[] tels = mc.getAppointTels().split(",");
                        for(int i = 0 ; i < tels.length ; i++) {
                            if (PatternUtils.isMobile(tels[i])) {
                                mobiles.add(tels[i]);
                            }
                        }
                    }

                    log.info("开始发送消息");
                    if (CollectionUtil.isNotEmpty(mus)) {//保存到u_msg_user表
                        for (MsgUser mu : mus) {
                            mum.insert(mu);//插入
                        }
                    }

                    if (CollectionUtil.isNotEmpty(emails)) {//发送邮件
                        String emailsStr = CollectionUtil.join(emails, ",");
                        String msgTitle = mc.getTitle();
                        String emailContent = mc.getEmailContent();
                        sendDelayEmail(emailsStr, msgTitle, emailContent, url);
                    }
                    if (CollectionUtil.isNotEmpty(mobiles)) {//发送短信
                        String mobileStr = CollectionUtil.join(mobiles, ",");
                        String telContent = mc.getTelContent();
                        Integer interfaceType = mc.getInterfaceType();
                        sendDelayMobile(mobileStr, telContent, interfaceType);
                    }
                } else {
                    log.error("根据CODE查询的MSGCONFIG对象不存在");
                }
            } else {
                log.error("发送消息失败，参数code或userdtos不存在");
            }
        } catch (Exception e) {
            log.error("sendMessage error", e);
        }
    }

    @Override
    public void sendDelayEmail(String emailsStr,String msgTitle,String emailContent,String url){
        emailContent = emailContent + (url == null ? "" : "\n<a href='"+url+"' target='_blank'>点击进入</a>");
        mqs.sendMailMessage(new MailParam(emailsStr ,msgTitle,emailContent));
    }
    @Override
    public void sendDelayMobile(String mobileStr,String telContent,Integer msgType){
        mqs.sendSMSMessage(new SmsParam(mobileStr, telContent , msgType));
    }

    @Override
    public void sendMessage(String configCode, String msgCode, Map<String, String> params) {
        Example exp = new Example(Config.class);
        exp.createCriteria().andEqualTo("code" , configCode);
        List<Config> configs = cm.selectByExample(exp);
        if(CollectionUtil.isNotEmpty(configs)){
            Config config = configs.get(0);
            String targets = config.getValue();
            List<UserMsgDto> users =  new ArrayList<UserMsgDto>();
            for (String s : targets.split(",")) {
                UserMsgDto umd = new UserMsgDto();
                if(PatternUtils.isEmail(s)){
                    umd.setEmail(s);
                }else if(PatternUtils.isMobile(s)){
                    umd.setMobile(s);
                }
                users.add(umd);
            }
            if(CollectionUtil.isNotEmpty(users)){
                sendMessage(msgCode , params , null , users);
            }
        }

    }

    @Override
    public void sendMessageWithOutUserId(String code, Map<String, String> params, String mobile, String email, boolean delay) {
        if(!StrUtil.isAllBlank(mobile, email)) {
            List<UserMsgDto> ulist = new ArrayList<>();
            ulist.add(new UserMsgDto(null, mobile, email));
            sendMessage(code, params, null, ulist, delay);
        }
    }

    @Override
    public void sendMessage(String code, Map<String, String> params, String url, Integer... userIds) {
        if(userIds!=null){
            sendMessage(code,params,url,Arrays.asList(userIds));
        }
    }

    @Override
    public void sendMessage(String code, Map<String, String> params, String url,boolean delay, Integer... userIds) {
        if(userIds!=null){
            sendMessage(code,params,url,Arrays.asList(userIds),delay);
        }
    }

    /**
     * 替换消息内容
     * @param content
     * @param params
     * @return
     */
    public String replaceContent(String content , Map<String , String > params){
        if(StrUtil.isNotBlank(content) && params != null && !params.isEmpty()){
            for (String s : params.keySet()) {
                String reg = "{"+s+"}";
                if(content.contains(reg)) {
                    content = content.replace(reg , Convert.toStr(params.get(s), ""));
                }
            }
            return content;
        }
        return content;
    }

	@Override
	public MsgConfig getMsgConfigByCode(String code) {
		return mm.selectOneByCode(code);
	}
}
